package in.co.codedoc.cg.velocity;

import in.co.codedoc.cg.CGAnnotationProcessor;

import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.parser.node.Node;

import com.sun.mirror.declaration.PackageDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;

public class ForEachPackageDirective extends CGBlockDirective
{
	public ForEachPackageDirective()
	{
		super();
	}

	@Override
	public String getName()
	{
		return "ForEachPackage";
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean render(InternalContextAdapter context, Writer writer,
			Node node) throws IOException, ResourceNotFoundException,
			ParseErrorException, MethodInvocationException
	{
		HashSet<PackageDeclaration> packages = new HashSet<PackageDeclaration>(); 
		for(TypeDeclaration td:CGAnnotationProcessor.getProcessor().getEnv().getTypeDeclarations())
		{
			packages.add(td.getPackage());
		}
		
		for(PackageDeclaration pd:packages)
		{
			context.put("currentPackage",pd);
			try
			{
				node.jjtGetChild(0).render(context, writer);
			}
			finally
			{
				context.remove("currentPackage");
			}
		}
		
		return true;
	}

}
